﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace UnitTest
{
    public class TimeoutTask
    {
        CancellationTokenSource Cts;
        double TimeoutSeconds;
        Func<Task> Func;
        public TimeoutTask(CancellationTokenSource cts, double timeoutSeconds, Func<Task> func)
        {
            Cts = cts;
            TimeoutSeconds = timeoutSeconds;
            Func = func;
        }

        public async Task<bool> ExecuteAsync()
        {
            Task task = Func.Invoke();
            Task delayTask = Task.Delay(TimeSpan.FromSeconds(TimeoutSeconds));
            Task completeTask = await Task.WhenAny(task, delayTask);
            if (completeTask == delayTask)
            {
                Cts.Cancel();
                return false;
            }
            else
            {
                return true;
            }
        }

    }
}
